PHP Laravel Redis caching examples

1. Directly with Redis class
config/app.php

‘providers’ => array(
‘Illuminate\Redis\RedisServiceProvider’,
),
‘aliases’ => array(
‘Redis’ => ‘Illuminate\Support\Facades\Redis’,
),

config/database.php

‘redis’ => array(
‘cluster’ => false,
‘default’ => array(
‘host’ => ‘127.0.0.1’,
‘port’ => 6379,
‘database’ => 0,
),
),

PHP code will look like this
$redis = \Redis::connection();
if ($redis->exists($cacheKey)) {
$results = json_decode($redis->get($cacheKey),true);
}
else {
$results =select_array_from_mysqldb( $dblink );
$redis->set($cacheKey,json_encode($results));
}

2. Through Cache class
config/cache.php

return array(
‘driver’ => ‘redis’,

‘prefix’ => ‘kleidoo’,
);

PHP code will look like this
$minutes = 60;
if (\Cache::has($cacheKey)) {
$results = json_decode(\Cache::get($cacheKey),true);
}
else {
$results =select_array_from_mysqldb( $dblink );
\Cache::put($cacheKey,json_encode($menutags),$minutes);
}

Leave a Reply